import 'package:flutter/material.dart';
import 'package:easy_refresh/easy_refresh.dart';
import '../animations/animation_config.dart';
import 'skeleton_widget.dart';
import 'advanced_animations.dart';

/// 列表数据状态枚举
enum SmartListState {
  initial,     // 初始状态
  loading,     // 首次加载中
  success,     // 加载成功
  empty,       // 空数据
  error,       // 加载错误
  loadingMore, // 加载更多中
  noMore,      // 没有更多数据
}

/// 智能列表组件
/// 集成下拉刷新、加载更多、状态管理、骨架屏和动画效果
class SmartListView<T> extends StatefulWidget {
  const SmartListView({
    super.key,
    required this.itemBuilder,
    required this.onRefresh,
    this.onLoadMore,
    this.items = const [],
    this.state = SmartListState.initial,
    this.separatorBuilder,
    this.padding,
    this.physics,
    this.shrinkWrap = false,
    this.reverse = false,
    this.scrollDirection = Axis.vertical,
    this.addAutomaticKeepAlives = true,
    this.addRepaintBoundaries = true,
    this.addSemanticIndexes = true,
    this.cacheExtent,
    this.controller,
    this.enableRefresh = true,
    this.enableLoadMore = true,
    this.enableAnimation = true,
    this.animationType = AnimationType.slideInUp,
    this.animationDelay = const Duration(milliseconds: 50),
    this.skeletonItemCount = 8,
    this.customSkeletonItem,
    this.emptyWidget,
    this.errorWidget,
    this.refreshText = '下拉刷新',
    this.refreshReadyText = '释放刷新',
    this.refreshingText = '正在刷新...',
    this.refreshedText = '刷新完成',
    this.refreshFailedText = '刷新失败',
    this.loadText = '上拉加载更多',
    this.loadReadyText = '释放加载',
    this.loadingText = '正在加载...',
    this.loadedText = '加载完成',
    this.loadFailedText = '加载失败',
    this.noMoreText = '没有更多了',
    this.onItemTap,
    this.headerBuilder,
    this.footerBuilder,
    this.gridDelegate,
    this.itemExtent,
    this.prototypeItem,
    this.findChildIndexCallback,
  });

  /// 必需参数
  final Widget Function(BuildContext context, T item, int index) itemBuilder;
  final Future<void> Function() onRefresh;
  final Future<void> Function()? onLoadMore;
  final List<T> items;
  final SmartListState state;

  /// 列表配置
  final Widget Function(BuildContext context, int index)? separatorBuilder;
  final EdgeInsetsGeometry? padding;
  final ScrollPhysics? physics;
  final bool shrinkWrap;
  final bool reverse;
  final Axis scrollDirection;
  final bool addAutomaticKeepAlives;
  final bool addRepaintBoundaries;
  final bool addSemanticIndexes;
  final double? cacheExtent;
  final EasyRefreshController? controller;

  /// 功能开关
  final bool enableRefresh;
  final bool enableLoadMore;
  final bool enableAnimation;

  /// 动画配置
  final AnimationType animationType;
  final Duration animationDelay;

  /// 骨架屏配置
  final int skeletonItemCount;
  final Widget? customSkeletonItem;

  /// 自定义状态组件
  final Widget? emptyWidget;
  final Widget? errorWidget;

  /// 刷新文本配置
  final String refreshText;
  final String refreshReadyText;
  final String refreshingText;
  final String refreshedText;
  final String refreshFailedText;

  /// 加载更多文本配置
  final String loadText;
  final String loadReadyText;
  final String loadingText;
  final String loadedText;
  final String loadFailedText;
  final String noMoreText;

  /// 事件回调
  final void Function(T item, int index)? onItemTap;

  /// 额外组件
  final Widget Function(BuildContext context)? headerBuilder;
  final Widget Function(BuildContext context)? footerBuilder;

  /// 网格布局
  final SliverGridDelegate? gridDelegate;

  /// 列表项配置
  final double? itemExtent;
  final Widget? prototypeItem;
  final int? Function(Key key)? findChildIndexCallback;

  @override
  State<SmartListView<T>> createState() => _SmartListViewState<T>();
}

class _SmartListViewState<T> extends State<SmartListView<T>>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;
  late EasyRefreshController _refreshController;

  @override
  void initState() {
    super.initState();
    _fadeController = AnimationConfig.createController(
      vsync: this,
      duration: AnimationConfig.fadeIn,
    );
    _fadeAnimation = AnimationConfig.createFadeAnimation(_fadeController);
    _refreshController = widget.controller ?? EasyRefreshController();
    
    _fadeController.forward();
  }

  @override
  void didUpdateWidget(SmartListView<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.state != oldWidget.state) {
      _handleStateChange();
    }
  }

  void _handleStateChange() {
    _fadeController.reset();
    _fadeController.forward();
  }

  @override
  void dispose() {
    _fadeController.dispose();
    if (widget.controller == null) {
      _refreshController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: _buildContent(),
    );
  }

  Widget _buildContent() {
    switch (widget.state) {
      case SmartListState.initial:
      case SmartListState.loading:
        return _buildLoadingState();
      
      case SmartListState.empty:
        return _buildEmptyState();
      
      case SmartListState.error:
        return _buildErrorState();
      
      case SmartListState.success:
      case SmartListState.loadingMore:
      case SmartListState.noMore:
        return _buildSuccessState();
    }
  }

  Widget _buildLoadingState() {
    return EasyRefresh(
      controller: _refreshController,
      onRefresh: widget.enableRefresh ? widget.onRefresh : null,
      header: _buildRefreshHeader(),
      child: _buildSkeletonList(),
    );
  }

  Widget _buildEmptyState() {
    return EasyRefresh(
      controller: _refreshController,
      onRefresh: widget.enableRefresh ? widget.onRefresh : null,
      header: _buildRefreshHeader(),
      child: _buildEmptyContent(),
    );
  }

  Widget _buildErrorState() {
    return EasyRefresh(
      controller: _refreshController,
      onRefresh: widget.enableRefresh ? widget.onRefresh : null,
      header: _buildRefreshHeader(),
      child: _buildErrorContent(),
    );
  }

  Widget _buildSuccessState() {
    return EasyRefresh(
      controller: _refreshController,
      onRefresh: widget.enableRefresh ? widget.onRefresh : null,
      onLoad: widget.enableLoadMore && 
              widget.onLoadMore != null && 
              widget.state != SmartListState.noMore 
          ? widget.onLoadMore 
          : null,
      header: _buildRefreshHeader(),
      footer: _buildLoadMoreFooter(),
      child: _buildDataList(),
    );
  }

  Widget _buildSkeletonList() {
    if (widget.customSkeletonItem != null) {
      return ListView.builder(
        padding: widget.padding,
        physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),
        shrinkWrap: widget.shrinkWrap,
        reverse: widget.reverse,
        scrollDirection: widget.scrollDirection,
        itemCount: widget.skeletonItemCount,
        itemBuilder: (context, index) => widget.customSkeletonItem!,
      );
    }

    return ListView.builder(
      padding: widget.padding,
      physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),
      shrinkWrap: widget.shrinkWrap,
      reverse: widget.reverse,
      scrollDirection: widget.scrollDirection,
      itemCount: widget.skeletonItemCount,
      itemBuilder: (context, index) => _buildAnimatedSkeleton(index),
    );
  }

  Widget _buildAnimatedSkeleton(int index) {
    if (!widget.enableAnimation) {
      return SkeletonLayouts.listItem();
    }

    return ListItemAnimations.animateListItem(
      child: SkeletonLayouts.listItem(),
      index: index,
      duration: AnimationConfig.listItemEnter,
      baseDelay: widget.animationDelay,
      type: widget.animationType,
    );
  }

  Widget _buildEmptyContent() {
    final emptyWidget = widget.emptyWidget ?? _buildDefaultEmptyWidget();
    
    return SingleChildScrollView(
      padding: widget.padding,
      physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),
      child: SizedBox(
        height: MediaQuery.of(context).size.height * 0.6,
        child: Center(child: emptyWidget),
      ),
    );
  }

  Widget _buildErrorContent() {
    final errorWidget = widget.errorWidget ?? _buildDefaultErrorWidget();
    
    return SingleChildScrollView(
      padding: widget.padding,
      physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),
      child: SizedBox(
        height: MediaQuery.of(context).size.height * 0.6,
        child: Center(child: errorWidget),
      ),
    );
  }

  Widget _buildDataList() {
    if (widget.gridDelegate != null) {
      return _buildGridView();
    }
    
    if (widget.separatorBuilder != null) {
      return _buildSeparatedListView();
    }
    
    return _buildListView();
  }

  Widget _buildListView() {
    return ListView.builder(
      padding: widget.padding,
      physics: widget.physics,
      shrinkWrap: widget.shrinkWrap,
      reverse: widget.reverse,
      scrollDirection: widget.scrollDirection,
      addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
      addRepaintBoundaries: widget.addRepaintBoundaries,
      addSemanticIndexes: widget.addSemanticIndexes,
      cacheExtent: widget.cacheExtent,
      itemExtent: widget.itemExtent,
      prototypeItem: widget.prototypeItem,
      findChildIndexCallback: widget.findChildIndexCallback,
      itemCount: _getTotalItemCount(),
      itemBuilder: (context, index) => _buildListItem(index),
    );
  }

  Widget _buildSeparatedListView() {
    return ListView.separated(
      padding: widget.padding,
      physics: widget.physics,
      shrinkWrap: widget.shrinkWrap,
      reverse: widget.reverse,
      scrollDirection: widget.scrollDirection,
      addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
      addRepaintBoundaries: widget.addRepaintBoundaries,
      addSemanticIndexes: widget.addSemanticIndexes,
      cacheExtent: widget.cacheExtent,
      findChildIndexCallback: widget.findChildIndexCallback,
      itemCount: widget.items.length,
      itemBuilder: (context, index) => _buildDataItem(index),
      separatorBuilder: widget.separatorBuilder!,
    );
  }

  Widget _buildGridView() {
    return GridView.builder(
      padding: widget.padding,
      physics: widget.physics,
      shrinkWrap: widget.shrinkWrap,
      reverse: widget.reverse,
      scrollDirection: widget.scrollDirection,
      addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
      addRepaintBoundaries: widget.addRepaintBoundaries,
      addSemanticIndexes: widget.addSemanticIndexes,
      cacheExtent: widget.cacheExtent,
      findChildIndexCallback: widget.findChildIndexCallback,
      gridDelegate: widget.gridDelegate!,
      itemCount: widget.items.length,
      itemBuilder: (context, index) => _buildDataItem(index),
    );
  }

  int _getTotalItemCount() {
    int count = 0;
    
    if (widget.headerBuilder != null) count++;
    count += widget.items.length;
    if (widget.footerBuilder != null) count++;
    
    return count;
  }

  Widget _buildListItem(int index) {
    int adjustedIndex = index;
    
    // Header
    if (widget.headerBuilder != null) {
      if (index == 0) {
        return widget.headerBuilder!(context);
      }
      adjustedIndex--;
    }
    
    // Footer
    if (widget.footerBuilder != null && 
        index == _getTotalItemCount() - 1) {
      return widget.footerBuilder!(context);
    }
    
    // Data items
    if (adjustedIndex >= 0 && adjustedIndex < widget.items.length) {
      return _buildDataItem(adjustedIndex);
    }
    
    return const SizedBox.shrink();
  }

  Widget _buildDataItem(int index) {
    if (index >= widget.items.length) return const SizedBox.shrink();
    
    final item = widget.items[index];
    Widget child = widget.itemBuilder(context, item, index);
    
    // 添加点击事件
    if (widget.onItemTap != null) {
      child = InkWell(
        onTap: () => widget.onItemTap!(item, index),
        child: child,
      );
    }
    
    // 添加动画
    if (widget.enableAnimation) {
      child = ListItemAnimations.animateListItem(
        child: child,
        index: index,
        duration: AnimationConfig.listItemEnter,
        baseDelay: widget.animationDelay,
        type: widget.animationType,
      );
    }
    
    return child;
  }

  Widget _buildDefaultEmptyWidget() {
    return EntranceAnimations.fadeIn(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox_outlined,
            size: 80,
            color: Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.5),
          ),
          const SizedBox(height: 24),
          Text(
            '暂无数据',
            style: Theme.of(context).textTheme.titleLarge?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '下拉可以刷新数据',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.7),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDefaultErrorWidget() {
    return EntranceAnimations.bounceIn(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 80,
            color: Theme.of(context).colorScheme.error.withOpacity(0.7),
          ),
          const SizedBox(height: 24),
          Text(
            '加载失败',
            style: Theme.of(context).textTheme.titleLarge?.copyWith(
              color: Theme.of(context).colorScheme.error,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '请检查网络连接或下拉重试',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant.withOpacity(0.7),
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: widget.onRefresh,
            icon: const Icon(Icons.refresh),
            label: const Text('重试'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.error,
              foregroundColor: Theme.of(context).colorScheme.onError,
            ),
          ),
        ],
      ),
    );
  }

  Header _buildRefreshHeader() {
    return ClassicHeader(
      dragText: widget.refreshText,
      armedText: widget.refreshReadyText,
      readyText: widget.refreshReadyText,
      processingText: widget.refreshingText,
      processedText: widget.refreshedText,
      failedText: widget.refreshFailedText,
      showMessage: false,
      textStyle: TextStyle(
        color: Theme.of(context).colorScheme.onSurface,
        fontSize: 14,
      ),
      iconTheme: IconThemeData(
        color: Theme.of(context).colorScheme.primary,
        size: 20,
      ),
      triggerOffset: 80,
      clamping: false,
      position: IndicatorPosition.above,
      processedDuration: const Duration(seconds: 1),
      spring: const SpringDescription(
        mass: 2.0,
        stiffness: 150,
        damping: 16,
      ),
      safeArea: false,
      infiniteOffset: null,
      hitOver: true,
      infiniteHitOver: false,
      hapticFeedback: true,
      triggerWhenReach: true,
      triggerWhenRelease: false,
      maxOverOffset: double.infinity,
    );
  }

  Footer _buildLoadMoreFooter() {
    if (widget.state == SmartListState.noMore) {
      return ClassicFooter(
        dragText: widget.noMoreText,
        armedText: widget.noMoreText,
        readyText: widget.noMoreText,
        processingText: widget.noMoreText,
        processedText: widget.noMoreText,
        failedText: widget.noMoreText,
        noMoreText: widget.noMoreText,
        showMessage: true,
        textStyle: TextStyle(
          color: Theme.of(context).colorScheme.onSurfaceVariant,
          fontSize: 14,
        ),
        iconTheme: IconThemeData(
          color: Theme.of(context).colorScheme.onSurfaceVariant,
          size: 16,
        ),
        triggerOffset: 40,
        clamping: true,
      );
    }

    return ClassicFooter(
      dragText: widget.loadText,
      armedText: widget.loadReadyText,
      readyText: widget.loadReadyText,
      processingText: widget.loadingText,
      processedText: widget.loadedText,
      failedText: widget.loadFailedText,
      noMoreText: widget.noMoreText,
      showMessage: false,
      textStyle: TextStyle(
        color: Theme.of(context).colorScheme.onSurface,
        fontSize: 14,
      ),
      iconTheme: IconThemeData(
        color: Theme.of(context).colorScheme.primary,
        size: 20,
      ),
      triggerOffset: 60,
      clamping: true,
      position: IndicatorPosition.above,
      processedDuration: const Duration(milliseconds: 300),
      spring: const SpringDescription(
        mass: 2.0,
        stiffness: 150,
        damping: 16,
      ),
      safeArea: false,
      infiniteOffset: 60,
      hitOver: true,
      infiniteHitOver: true,
      hapticFeedback: true,
      triggerWhenReach: true,
      triggerWhenRelease: false,
      maxOverOffset: double.infinity,
    );
  }

  /// 获取刷新控制器
  EasyRefreshController get refreshController => _refreshController;
  
  /// 手动触发刷新
  void triggerRefresh() => _refreshController.callRefresh();
  
  /// 手动触发加载更多
  void triggerLoadMore() => _refreshController.callLoad();
  
  /// 完成刷新
  void finishRefresh({IndicatorResult result = IndicatorResult.success}) {
    _refreshController.finishRefresh(result);
  }
  
  /// 完成加载更多
  void finishLoadMore({IndicatorResult result = IndicatorResult.success}) {
    _refreshController.finishLoad(result);
  }
  
  /// 重置刷新状态
  void resetRefresh() => _refreshController.resetHeader();
  
  /// 重置加载更多状态
  void resetLoadMore() => _refreshController.resetFooter();
}